ページ 1 / 1
クラスメンバの無名共用体のstd::string
Posted: 2017年8月12日(土) 07:41
by aguna
このコードが実行時エラーになるのですが、仕様でしょうか?
環境は、VC++ visualstudio2017です。
コード:
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {};
~A() {};
std::string str1;
union { std::string str2; };
};
int main() {
A a;
a.str1 = "Hello";
a.str2 = a.str1;
}
最後の代入のところでエラーになります。
Re: クラスメンバの無名共用体のstd::string
Posted: 2017年8月12日(土) 08:42
by sleep
共用体の制限解除(C++11)
・共用体の非静的メンバ変数として定義されている非自明なコンストラクタおよびデストラクタを持つ型のオブジェクトに対しては、配置new構文でオブジェクトを構築し、明示的にデストラクタを呼び出す必要がある
コード:
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {};
// ~A() {};
~A() { str2.~basic_string(); };
std::string str1;
union { std::string str2; };
};
int main() {
A a;
a.str1 = "Hello";
// a.str2 = a.str1;
new (&a.str2) std::string{ a.str1 };
}
Re: クラスメンバの無名共用体のstd::string
Posted: 2017年8月12日(土) 08:47
by aguna
なるほど!構造体と同じようにはできないんですね!
unionは謎だらけですね…
どうもありがとうございました!