Using placement new to update a reference member?

前端 未结 2 766
野趣味
野趣味 2021-01-14 18:45

Is the following code legal in C++?

template
class Foo {
public:
    Foo(T& v) : v_(v) {}

private:
    T& v_;
};

int a = 10;
Foo         


        
2条回答
  •  终归单人心
    2021-01-14 19:32

    It may be legal, but it's incredibly poor style. The argument to placement new is a void*, so you're telling C++ to reinterpret_cast the address of f as a void*, then using that as the location to construct something new - overwriting the original f.

    Basically, don't do that.

提交回复
热议问题