新增[size]对象(args ..)在数组new [-fpermissive]中添加圆括号初始化器

new[size] object(args ... ) , GCC parenthesized initializer in array new [-fpermissive]

本文关键字:-fpermissive 添加 初始化 new 圆括号 对象 size args 新增 数组      更新时间:2023-10-16

我的代码有一个问题,我真的不明白。

我使用«gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)»


编辑:我用这一行来编译
g++ -g -std=c++0x -o "GeneticEngine.o" -c "GeneticEngine.cpp" 

错误如下:

GeneticEngine.tpl:16:5: erreur: parenthesized initializer in array new [-fpermissive]

这是我的(最小化)代码:


GeneticEngine.hpp

#include "GeneticThread.hpp"
template <class T>
class GeneticEngine
{
    public:
        template <typename ... Args>
        GeneticEngine(int nb_threads,float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args);
        /* Other code */

    private:
        GeneticThread<T>* islands; /* Cause of error */
        int size;
};
#include "GeneticEngine.tpl"

GeneticEngine.tpl

template <class T>
template <typename ... Args>
GeneticEngine<T>::GeneticEngine(int nb_threads,float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args) : size(nb_threads)
{
/*next line is 16 : Error */
 islands = new  GeneticThread<T>[size](taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...);
};

GeneticThread.hpp

template <class T>
class GeneticThread
{
    public:
        template <typename ... Args>
        GeneticThread(float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args)
        { /* code ... */ };
     /* Other code */
};

我读过这个(使用模板时初始化数组),但它不完全相同。

如果你有一个想法来修复它,而不需要:[最后我使用这个:/]

GeneticThread<T>** islands;
islands = new  GeneticThread<T>*[size];
for(int i=0;i<size;++i)
   islands[i] = new GeneticThread<T>(taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...);

我想有:

 GeneticThread<T>* islands;

有办法吗??

我试一试:

islands = new  (GeneticThread<T>[size](taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...));

 islands = new  GeneticThread<T>(taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...)[size];

但它不工作。


谢谢。

不能为new . ly分配的数组使用非默认构造函数。

不像这样使用new,而是使用vector并将一个正确构造的对象传递给vector构造函数!即使你不需要调整内存大小,vector也会确保你的内存被妥善管理,不会泄露。

例如:

std::vector<GeneticThread<T>*> islands;

:

GeneticEngine<T>::GeneticEngine(int nb_threads,float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args)
: size(nb_threads), islands(size, GeneticThread<T>(taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...))
{
};