6

ときどき gcc は、boost::optional での作業について警告を出すことがありますが、これは誤検知であると想定しています (ここで説明されているようにhttps://github.com/boostorg/optional/issues/72 )。

しかし、valgrind は実行時に同じ問題を報告するようになりました。

//Foo.hpp
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <cstdio>
#include <string>

extern "C" {
typedef struct FooOpaque FooOpaque;

FooOpaque *Foo_new();

void Foo_delete(const FooOpaque *self);
}

class Foo {
public:
  explicit Foo(FooOpaque *o) noexcept : self_(o) {}
  Foo(const Foo &) = delete;
  Foo &operator=(const Foo &) = delete;

  Foo(Foo &&o) noexcept : self_(o.self_) { o.self_ = nullptr; }
  Foo &operator=(Foo &&o) noexcept {

    assert(this != &o);
    free_mem(this->self_);
    self_ = o.self_;
    o.self_ = nullptr;
    return *this;
  }
  ~Foo() noexcept { free_mem(this->self_); }

private:
  static void free_mem(FooOpaque *&p) noexcept {
    //    printf("test\n");
    if (p != nullptr) {
      Foo_delete(p);
    }
    p = nullptr;
  }

  FooOpaque *self_ = nullptr;
};

boost::variant<boost::optional<Foo>, std::string> f_res_opt(int var);
//Foo.cpp
#include <cassert>
#include <cstdint>
#include <cstring>

#include "Foo.hpp"

extern "C" {
struct FooOpaque {
  int data;
};

FooOpaque *Foo_new() {
  printf("Foo_new begin\n");
  auto p = new FooOpaque;
  p->data = 17;
  return p;
}

void Foo_delete(const FooOpaque *self) {
  assert(self != nullptr);
  printf("Foo_new delete\n");
  delete self;
}
}

boost::variant<boost::optional<Foo>, std::string> f_res_opt(int var) {
  switch (var) {
  case 0:
    return {boost::optional<Foo>{Foo{Foo_new()}}};
  case 1:
    return {boost::optional<Foo>{boost::none}};
  case 2:
    return {std::string{}};
  default:
    std::abort();
  }
}
// main.cpp
#include "Foo.hpp"

int main() {

  auto res1 = f_res_opt(0);
  auto res1_ok = boost::get<boost::optional<Foo>>(boost::move(res1));

  printf("step 2\n");

  auto res2 = f_res_opt(1);

  auto res2_ok = boost::get<boost::optional<Foo>>(boost::move(res2));

  printf("step 3\n");

  auto res3 = f_res_opt(2);

  auto res3_ok = boost::get<std::string>(boost::move(res3));
}

valgrind と gcc は問題を次のように報告します。

auto res2_ok = boost::get<boost::optional<Foo>>(boost::move(res2));

その可能性Foo::free_memは、ユニット化されたメモリに使用される可能性があります。

Foo::free_mem gcc 警告 (9.1.0)で printf を有効にすると消え、valgrind (3.15) は問題を報告しません。

私はそのような方法でgccで例をコンパイルします:

g++ -ggdb -O3 -Wall -std=c++11 -Wextra main.cpp foo.cpp

それでは、私のコード、boost::optional、または valgrind と g++ の同時エラーで何が起こっているのでしょうか?

間違ったコードを生成する g++ のこのバグで、valgrind もエラーについて文句を言うのでしょうか?

4

0 に答える 0